
import axios from 'axios'
import QsStringify from 'qs-stringify';
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
 import  { baseUrl } from './config'

// const baseURL = '/api'
// create an axios instance
const service = axios.create({
    baseURL: '/api',    // url = base url + request url
    withCredentials: true, // send cookies when cross-domain requests
    timeout: 5000 //请求超时时间
})

/**
 * get请求
 * @param url
 * @param body 参数，字典格式 {a:a,b:b}
 * @param headers
 * @param config
 * @returns {Promise<Response>}
 */
export function sendGetRequest(url, body = {}, headers = {}, config = {}) {
    url = url + (url.endsWith('?') ? '' : '?');
    url = url +  QsStringify(body);
    headers['Authorization'] = getToken()||''
    return sendRequest(url, 'GET', null, headers, config);
}


/**
 * post请求 json格式
 * @param url 接口地址
 * @param body 参数，字典格式 {a:a,b:b}
 * @param headers 报头
 * @param config
 * @returns {Promise<Response>}
 */
export function sendPostRequest (url, body = {}, headers = {}, config = {}) {
    headers['Content-Type'] = 'application/json';
    headers['Authorization'] = getToken()||''
    return sendRequest(url, 'POST', JSON.stringify(body), headers, config);
}




// 全局统一的请求接口
function sendRequest (url, method, body, headers, config) {
    console.log('全局统一的请求接口')
    const option = {
        url: url,
        method: method,
        headers: {}
    };
    if (body) {
        option['data'] = body;
    }

    if (headers) {
        for (const key in headers) {
            if (headers.hasOwnProperty(key)) {
                option['headers'][key] = headers[key];
            }
        }
    }
    if (config) {
        for (const key in config) {
            if (config.hasOwnProperty(key)) {
                option[key] = config[key];
            }
        }
    }
    console.log(option)
    return service(option)
    // return service(option)

}

// 请求拦截器
// service.interceptors.request.use(
//   config => {
//     // 在发送请求之前做些什么

//     if (store.getters.token) {
//       // 每个请求携带token 
//       // ['X-Token'] is a custom headers key
//       // please modify it according to the actual situation
//       config.headers['X-Token'] = getToken()
//     }
//     return config
//   },
//   error => {
//     // 处理请求错误
//     console.log(error) // for debug
//     return Promise.reject(error)
//   }
// )

// 响应拦截器
service.interceptors.response.use(
    /**
     * 如果想获取http信息，如头或状态
     * 请  return response => response
    */
    /**
     * 通过自定义代码确定请求状态
     * You can also judge the status by HTTP Status Code
     */
    response => {
        console.log(response)
        const res = response.data
        // 如果自定义代码不是2000000，则判断为错误
        if (res.status !== 2000000) {
            Message({
                message: res.msg || 'Error',
                type: 'error',
                duration: 5 * 1000
            })

            // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
            if (res.status === 50008 || res.status === 50012 || res.status === 50014) {
                MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    store.dispatch('user/resetToken').then(() => {
                        location.reload()
                    })
                })
            }
            return Promise.reject(new Error(res.message || 'Error'))
        } else {
            return res.res
        }
    },
    error => {
        console.log('err' + error) // for debug
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)

export default {
    sendGetRequest,
    sendPostRequest
} 
